<!-- 补单 -->
<template>
  <app-layout>
    <view class="add-order">
    <view class="add-order-content">
      <!-- 信息 -->
      <view class="order-info">
        <view class='order-item'>
          <view class="form-label">
            商品名称或服务名称
            <text>*</text>
          </view>
          <input class='add-input box-grow-1' placeholder-style="color: #cdcdcd" placeholder="请输入商品名称" v-model='form.name'/>
        </view>
        <view class='order-item'>
          <view class="form-label">
            消费者手机号码
            <text>*</text>
          </view>
          <input type="number" maxlength="11" class='add-input box-grow-1' placeholder-style="color: #cdcdcd" placeholder="请输入消费者手机号码" v-model='form.phone'/>
        </view>
        <view class='order-item'>
          <view class="form-label">
            现场实收金额
            <text>*</text>
          </view>
          <input class='add-input box-grow-1' placeholder-style="color: #cdcdcd" placeholder="请输入金额"  @input="testMoney" v-model='form.money'/>
        </view>
        <view class='order-item'>
          <view class="form-label">
            上传凭证
            <text>*</text>
          </view>
          <view class="img-list">
            <view @click.stop='addImg'>
              <image class="image" src="/static/image/cart/can-be-added.png"></image>
            </view>
            <view class="pai_img" v-for="(item,index) in imgArr" :key="index">
              <image :src="item.pic_url"  @tap="previewImage(index,1)"></image>
              <image class="deteles" src="/static/image/plugins/delete.png" @tap="deteleImage($event)" :data-index="index"></image>
            </view>
          </view>
        </view>
      </view>
      <!-- 积分 -->
      <view class="order-integral cross-center">
        <view class="integral-item consumer">
          <view class="integral-type">消费者可获得积分</view>
          <view class="integral-number">{{consumerIntegral}}</view>
        </view>
        <view class="integral-item business">
          <view class="integral-type">商家可获得积分</view>
          <view class="integral-number">{{businessIntegral}}</view>
        </view>
      </view>
      <view class="add-order-bottom" :class="{'isDisabled': isDisabled}" @click="addOrder">确认补单</view>
    </view>
  </view>
  </app-layout>
</template>

<script>
import uploadFile from '@/core/upload.js';
export default {
  name: "add-order",
  data() {
    return {
      mch_id: '',
      form: {
        name: '',
        phone: '',
        money: '',
      },
      img: [],
      imgArr: []
    }
  },
  onLoad(options) {
    let that = this;
    that.mch_id = options.mch_id; // 商铺id
  },
  computed: {
    isDisabled() {
      if(this.form.name&&this.form.phone&&this.form.money&&this.imgArr.length){
        return true
      }else{
        return false
      }
    },
    // 消费者可获得积分
    consumerIntegral() {
      return this.form.money? this.form.money: 0;
    },
    // 商家可获得积分
    businessIntegral() {
      return this.form.money?Math.round(this.form.money*0.15 * 100)/100:0;
    },
  },
  methods: {
    testMoney(e) {
      let that = this;
      let price = e.detail.value
      if (price.indexOf(".") == 0) {
        // 首位小数点情况
        price = price.replace(/[^$#$]/g, "0.");
        price = price.replace(/\.{2,}/g, ".");
      }
      price = price.match(/^\d*(\.?\d{0,2})/g)[0] || null;
      // 重新赋值
      this.$nextTick(() => {
        that.form.money = price;
      });
    },
    // 确认补单
    addOrder() {
      let that = this;
      if(!that.form.name) {
        uni.showToast({
          title: '请输入商品名称',
          icon: 'none',
        });
        return false;
      }
      if(!that.form.phone) {
        uni.showToast({
          title: "手机号码有误",
          icon: "none"
        })
        return false
      }
      if(!(/^1[3456789]\d{9}$/.test(that.form.phone))) {
        uni.showToast({
          title: "手机号码有误",
          icon: "none"
        })
        return false
      }
      if(!that.imgArr.length) {
        uni.showToast({
          title: "请上传凭证",
          icon: "none"
        })
        return false
      }
      that.$showLoading({text: '正在提交'});
      that.$request({
        url: that.$api.scan_code_pay.addOrder,
        method: 'post',
        data: {
          title: that.form.name,
          mobile: that.form.phone,
          price: that.form.money,
          mch_id: that.mch_id,
          image_list: that.imgArr,
          remark: '',
          coupon_id: 0
        },
      }).then(e => {
        that.$hideLoading();
        if (e.code === 0) {
          that.$payment.pay(e.data.pay_id).then(payMsg => {
            that.$store.commit('scanCode/mutSetUserCoupon', '');
            // 支付成功
            uni.showModal({
              title: '提示',
              content: "支付成功",
              showCancel: false,
              success() {
                uni.navigateTo({
                  url: '/pages/order-submit/pay-result?payment_order_union_id=' + e.data.pay_id + '&plugin=scan_code_pay'
                })
              },
            });
          }).catch(payMsg => {
            // 支付失败
            that.$showLoading({text: '取消中'});
            that.$request({
              url: that.$api.scan_code_pay.cancel,
              data: {
                pay_id: e.data.pay_id,
              },
              method: 'POST',
            }).then(info => {
              that.$hideLoading();
            }).catch(info => {
              that.$hideLoading();
              uni.showModal({title: '提示', content: info.msg});
            })
          });
        } else {
          uni.showModal({title: '提示', content: e.msg});
        }
      }).catch(e => {
        that.$hideLoading();
      });
    },
    // 上传图片
    addImg() {
      let that = this;
      let num = 9 - that.imgArr.length;
      // #ifdef MP
      uni.chooseImage({
        count: num,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success(res) {
          // tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFilePaths;
          let img = that.imgArr;
          tempFilePaths.forEach(function (row, index) {
            uni.showLoading({
              mask: true,
              title: '上传中...'
            });
            let fileName = '';
            // #ifdef MP-BAIDU
            fileName = row.substr(row.lastIndexOf('/') + 1);
            // #endif
            uploadFile({
              url: that.$api.upload.file,
              filePath: row,
              fileType: 'image',
              fileName: fileName,
              mch_id: 0
            }).then(res => {
              let imgInfo = null;

              // #ifndef MP-BAIDU
              imgInfo = JSON.parse(res.data);
              // #endif

              // #ifdef MP-BAIDU
              imgInfo = res.data;
              // #endif

              if (imgInfo.code === 0) {
                img.push({
                  pic_url: imgInfo.data.url,
                  id: imgInfo.data.id
                })
                that.img.push(imgInfo.data.url);
              }

              that.imgArr = img;
              if (index === tempFilePaths.length - 1) {
                uni.hideLoading();
              }
            }).catch(e => {
              if (e && e.errMsg) {
                uni.showModal({
                  title: '错误',
                  content: e.errMsg,
                  showCancel: false,
                });
              }
            })
          })
        }
      })
      // #endif

      // #ifdef H5
      uni.chooseImage({
        count: Number(num),
        success: function(e) {
          uni.showLoading({
            mask: true,
            title: '上传中...'
          });
          for (let i in e.tempFilePaths) {
            if (i >= (num - that.imgArr.length)) {
              break;
            }
            let image = new Image();
            image.src = e.tempFilePaths[i];
            image.onload = () => {
              let canvas = document.createElement("canvas");
              canvas.width = image.width;
              canvas.height = image.height;
              let ctx = canvas.getContext("2d");
              ctx.drawImage(image, 0, 0, image.width, image.height);
              let ext = image.src.substring(image.src.lastIndexOf(".") + 1).toLowerCase();
              let dataURL = canvas.toDataURL("image/" + ext);
              uploadFile({
                url: that.$api.upload.file,
                maxNum: num,
                success: function({res, header}) {
                  that.$request({
                    url: that.$api.upload.file + '&name=base64',
                    header: header,
                    method: 'post',
                    data: {
                      database: dataURL
                    }
                  }).then(res => {
                    uni.hideLoading();
                    if (res.code === 0) {
                      that.imgArr.push({
                        pic_url: res.data.url,
                        id: res.data.id
                      })
                      that.img.push(res.data.url)
                      // if (index === e.tempFilePaths.length - 1) {
                      //     uni.hideLoading();
                      // }
                    } else {
                      uni.showModal({
                        title: '',
                        content: res.msg,
                        showCancel: false,
                      });
                    }
                  })
                }
              });
            };
          }
        }
      });
      // #endif
    },
    // 预览图片
    previewImage: function(val) {
      var urls = this.img
      const current = val
      uni.previewImage({
        urls,
        current,
        loop: true,
        indicator: 'number'
      })
    },
    // 删除照片
    deteleImage(e) {
      var _this = this;
      uni.showModal({
        title: '删除照片',
        content: '确定要删除这张照片吗？',
        cancelText: '取消',
        confirmText: '确定',
        success: res => {
          if (res.confirm) {
            _this.imgArr.splice(e.currentTarget.dataset.index, 1);
            _this.img.splice(e.currentTarget.dataset.index, 1);
          }
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.add-order {
  .add-order-content {
    padding: 0 #{32upx};
  }
  .order-info {
    background: #FFFFFF;
    border-radius: #{40upx};
    padding: #{40upx};
    margin-top: #{20upx};
    .order-item {
      .form-label {
        position: relative;
        font-weight: bold;
        font-size: #{28upx};
        margin: #{30upx} 0;
        text {
          color: #DE4335;
        }
      }
      .add-input {
        font-size: #{28upx};
        height: auto;
        padding-bottom: #{20upx};
        border-bottom: 2upx solid #cdcdcd;
      }
      .img-list {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        .image {
          width: #{196upx};
          height: #{196upx};
          border-radius: #{40upx};
        }
        .pai_img {
          width: #{190upx};
          height: #{190upx};
          border-radius: #{40upx};
          margin-left: 10upx;
          margin-bottom: 10upx;
          position: relative;

          image {
            width: 100%;
            height: 100%;
            border-radius: #{40upx};
          }

          .deteles {
            width: 30upx;
            height: 30upx;
            position: absolute;
            top: 0;
            right: 0
          }
        }
      }
    }
  }
  .order-integral {
    background: #FFFFFF;
    border-radius: #{40upx};
    padding: #{30upx} #{65upx};
    justify-content: space-between;
    margin-top: #{20upx};
    .integral-item {
      text-align: center;
      .integral-type {
        font-size: #{28upx};
        color: #333333;
        font-weight: bold;
        margin-bottom: #{10upx};
      }
      .integral-number {
        max-width: #{220rpx};
        font-size: #{60upx};
        color: #DE4335;
        overflow-y: auto;
      }
    }
  }
  .add-order-bottom {
    height: 84upx;
    line-height: 84upx;
    color: #ffffff;
    font-size: 36upx;
    border-radius: 42upx;
    margin-top: 38upx;
    text-align: center;
    background: rgba(222, 67, 53, 0.5);
  }
  .isDisabled {
    background: rgba(222, 67, 53, 1);
    box-shadow: 0px 6px 12px rgba(222, 67, 53, 0.5);
  }
}
</style>